package com.gph.saviorframework.es.core.query;

import org.springframework.data.domain.Pageable;
import org.springframework.util.Assert;

public class CriteriaQuery extends AbstractQuery {

	private Criteria criteria;

	private CriteriaQuery() {
	}

	public CriteriaQuery(Criteria criteria) {
		this(criteria, null);
	}

	public CriteriaQuery(Criteria criteria, Pageable pageable) {
		this.criteria = criteria;
		this.pageable = pageable;
		if (pageable != null) {
			this.addSort(pageable.getSort());
		}
	}

	public static final Query fromQuery(CriteriaQuery source) {
		return fromQuery(source, new CriteriaQuery());
	}

	public static <T extends CriteriaQuery> T fromQuery(CriteriaQuery source, T destination) {
		if (source == null || destination == null) {
			return null;
		}

		if (source.getCriteria() != null) {
			destination.addCriteria(source.getCriteria());
		}

		if (source.getSort() != null) {
			destination.addSort(source.getSort());
		}

		return destination;
	}

	@SuppressWarnings("unchecked")
	public final <T extends CriteriaQuery> T addCriteria(Criteria criteria) {
		Assert.notNull(criteria, "Cannot add null criteria.");
		if (this.criteria == null) {
			this.criteria = criteria;
		} else {
			this.criteria.and(criteria);
		}
		return (T) this;
	}

	public Criteria getCriteria() {
		return this.criteria;
	}
}
